package org.qy.star_server.controller;

import lombok.extern.slf4j.Slf4j;
import org.qy.star_server.core.BrokerServer;
import org.qy.star_server.core.Queue;
import org.qy.star_server.core.VirtualHost;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yinger
 * @description TODO
 * @date 2024/3/31 15:58
 **/
@RestController
@RequestMapping("/queue")
@Slf4j
public class QueueController {

    @RequestMapping("/add")
    public boolean addQueue(Queue queue) {
        System.out.println("添加队列：" + queue);
        try {
            if(! BrokerServer.disk.insertQueue(queue.getUsername(), queue.getVirtualHostName(),queue.getQueueName(),queue.isDurable(),queue.isExclusive(),queue.isAutoDelete(),null)) {
                return false;
            }
             BrokerServer.memory.insertQueue(queue.getUsername(), queue.getVirtualHostName(),queue.getQueueName(),queue.isDurable(),queue.isExclusive(),queue.isAutoDelete());
        } catch (Exception e) {
            log.error("添加队列失败！", e);
            return false;
        }
        return true;
    }

    @RequestMapping("/v-hostAll")
    public List<Queue> getQueueListWithinVirtualHost(String virtualHostName, String username) {
        List<Queue> queues = null;
        if ("All".equals(virtualHostName)) {
            // 获取该用户的所有虚拟机
            List<VirtualHost> virtualHosts =  BrokerServer.memory.selectVirtualHostByUser(username);
            queues = new ArrayList<>();
            for (VirtualHost v : virtualHosts) {
                List<Queue> queueList =  BrokerServer.memory.selectQueueByVirtualHost(username,virtualHostName);
                queues.addAll(queueList);
            }
        } else {
            queues =  BrokerServer.memory.selectQueueByVirtualHost(username,virtualHostName);
        }
        for (Queue q : queues) {
            q.setMessageNumber( BrokerServer.memory.getQueueMessageCount(q.getUsername(),q.getVirtualHostName(),q.getQueueName()));
        }
        return queues;
    }
}
